package wn.lizzy.thread.ball;

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

/**
 * 一个球起一个独立的线程，可以明显提高球的反应能力，允许多个球同时运行，
 * 而且点击close可以及时响应，如果用单线程，性能极差，不能及时响应用户点击。
 * @author cuilijian
 *
 */
@SuppressWarnings("serial")
public class BounceFrame extends JFrame{

	private BallComponent component;
	
	public BounceFrame(){
		component = new BallComponent();
		add(component, BorderLayout.CENTER);
		JPanel buttonPanel = new JPanel();
		
		addButton(buttonPanel, "Start", new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent arg0) {
				addBall();
			}
		});
		
		addButton(buttonPanel, "Close", new ActionListener(){

			@Override
			public void actionPerformed(ActionEvent e) {
				System.exit(0);
			}
		});
		add(buttonPanel, BorderLayout.SOUTH);
		pack();
	}
	
	public void addButton(Container c, String title, ActionListener listener){
		JButton button = new JButton(title);
		c.add(button);
		button.addActionListener(listener);
	}
	
	public void addBall(){
		Ball ball = new Ball();
		component.add(ball);
		Runnable r = new BallRunnable(ball, component);
		Thread t = new Thread(r);
		t.start();
	}
}
